package com.kuhh.controller.ajax;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuhh.pojo.ProfessionCourse;
import com.kuhh.pojo.Scores;
import com.kuhh.service.IProfessionCourseService;
import com.kuhh.service.IScoresService;
import com.kuhh.service.impl.ProfessionCourseServiceImpl;
import com.kuhh.service.impl.ScoresServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getScores")
public class GetScores extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String courseNo = request.getParameter("courseNo");
        String studentNo = request.getParameter("studentNo");
        String id = request.getParameter("id");

        IScoresService scoresService = new ScoresServiceImpl();
        Scores scores = scoresService.getScoreByCourseNoAndStudentNo(courseNo, studentNo);
        if (scores == null){
            scores = scoresService.getScoreById(Integer.parseInt(id));
        }
        IProfessionCourseService professionCourseService = new ProfessionCourseServiceImpl();
        ProfessionCourse course = professionCourseService.getProfessionCourseByNo(scores.getCourseNo());
        String professionNo = course.getProfessionNo();
        Map<String, Object> map = new HashMap<>();
        map.put("professionNo",professionNo);
        map.put("scores",scores);

        response.setContentType("text/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        writer.print(objectMapper.writeValueAsString(map));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
